/**
功能点：

1. 新增分类
2. 删除分类
3. 编辑分类

4. 新增命令
5. 删除命令
6. 编辑命令
*/
<template>
  <div>
    <!-- 上方操作区域 -->
    <div
        style="margin: 20px 0 30px; padding: 20px; border-radius: 16px; background-color: #f5f7fa; box-shadow: 0 4px 12px rgba(0,0,0,0.04);">
      <div style="display: flex; align-items: center; gap: 20px;">
        <el-button type="primary" @click="addCommand">添加命令</el-button>
        <el-input v-model="searchCmdKeyword" placeholder="命令关键词" style="width: 220px;"/>
        <el-input v-model="searchDesKeyword" placeholder="描述关键词" style="width: 220px;"/>
        <el-button @click="searchReset">重置</el-button>
        <el-button type="primary" @click="searchCommands">搜索</el-button>
      </div>
    </div>

    <!-- 下方左右布局 -->
    <div style="display: flex; gap: 25px;">
      <!-- 左边分类列表 -->
      <div
          style="width: 280px; height: calc(100vh - 220px); padding: 20px; border-radius: 16px; background-color: #f5f7fa; box-shadow: 0 4px 12px rgba(0,0,0,0.04); overflow: auto;">
        <el-tree
            :data="treeCategories"
            :default-expanded-keys="['0']"
            :props="{ label: 'name', children: 'children' }"
            class="custom-tree"
            node-key="id"
            @node-click="handleCategorySelect"
            @node-contextmenu="showContextMenu"
        />
      </div>

      <!-- 右边命令表格 -->
      <div
          style="flex: 1; height: calc(100vh - 220px); padding: 20px; border-radius: 16px; background-color: #f5f7fa; box-shadow: 0 4px 12px rgba(0,0,0,0.04); overflow-y: auto;">
        <el-table :data="commands" border style="width: 100%;">
          <el-table-column label="命令内容" prop="command">
            <template #default="{ row }">
              <el-input v-model="row.command" type="textarea"/>
            </template>
          </el-table-column>
          <el-table-column label="命令描述" prop="description">
            <template #default="{ row }">
              <span>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="categoryName">
            <template #default="{ row }">
              <span>{{ row.categoryName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime">
            <template #default="{ row }">
              <span>{{ row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime">
            <template #default="{ row }">
              <span>{{ row.updateTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="editCommand(scope)">编辑</el-button>
              <el-popconfirm
                  cancel-button-text="否"
                  confirm-button-text="是"
                  icon-color="#626AEF"
                  title="确认要删除吗?"
                  @confirm="deleteCommand(scope)"
              >
                <template #reference>
                  <el-button style="color: red" type="text">删除</el-button>
                </template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑命令对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="currentCommand">
        <el-form-item label="命令内容" prop="command">
          <el-input v-model="currentCommand.command" rows="4" type="textarea"/>
        </el-form-item>
        <el-form-item label="命令描述" prop="description">
          <el-input v-model="currentCommand.description" placeholder="请输入命令描述" rows="2" type="textarea"/>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-tree-select
              v-model="currentCommand.category"
              :data="treeCategories"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="请选择分类"
              check-strictly=true
              style="width: 100%"
          />
          <el-button style="margin-left: 10px;" type="text" @click="showAddCategoryDialog = true">+ 新增分类</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCommand">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增分类对话框 -->
    <el-dialog v-model="showAddCategoryDialog" title="添加新分类" width="300px">
      <el-form :model="newCategory">
        <el-form-item :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]" label="分类名称"
                      prop="name">
          <el-input v-model="newCategory.name" placeholder="请输入新分类名称"/>
        </el-form-item>
        <el-form-item label="父分类" prop="pid">
          <el-tree-select
              v-model="newCategory.pid"
              :data="treeCategories"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="选择父分类"
              check-strictly=true
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCategoryDialog = false">取消</el-button>
        <el-button type="primary" @click="addNewCategory">确定</el-button>
      </template>
    </el-dialog>
    <!-- 分类右键菜单 -->
    <div v-if="contextMenuVisible"
         :style="{ position: 'fixed', left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px', zIndex: 1000, background: '#fff', border: '1px solid #ccc', borderRadius: '4px', boxShadow: '2px 2px 10px rgba(0,0,0,0.1)' }">
      <div style="padding: 8px 12px; cursor: pointer;" @click="renameCategory">编辑分类</div>
      <div style="padding: 8px 12px; cursor: pointer; color: #f56c6c;" @click="deleteCategory">删除分类</div>
      <div style="padding: 8px 12px; cursor: pointer;" @click="addCommandToCategory">在此分类上添加命令</div>
    </div>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="renameDialogVisible" title="编辑分类" width="300px">
      <el-form :model="renameCategoryForm">
        <el-form-item :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]" label="分类名称"
                      prop="name">
          <el-input v-model="renameCategoryForm.name" placeholder="分类名称"/>
        </el-form-item>
        <el-form-item label="父分类" prop="pid">
          <el-tree-select
              v-model="renameCategoryForm.pid"
              :data="treeCategories"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="选择父分类"
              check-strictly=true
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRename">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, computed, onMounted, h, watch} from 'vue'
import {
  deleteCommandCategory,
  deleteCommandItem,
  getAllCommandCategoryList,
  getAllCommandList, queryCommandList, saveOrUpdateCommandCategory,
  saveOrUpdateCommandItem
} from "@/api/webShell/commonScripts";
import {message} from "@/utils/ElmessasgeUtils";
import {ElMessageBox, ElTreeSelect} from "element-plus";

// 从后端获取分类数据
const categoriesFromBackend = ref([])
// 默认加载全部命令数据
const commands = ref([])


// 当前选中分类
const selectedCategoryId = ref('0')
// 搜索关键词
const searchCmdKeyword = ref('')
const searchDesKeyword = ref('')

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('添加命令')
const currentCommand = ref({command: '', description: '', category: 2})
// 新增分类相关
const showAddCategoryDialog = ref(false)
const newCategory = ref({name: '', pid: '0'})
// 右键菜单相关
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({x: 0, y: 0})
const selectedCategoryItem = ref(null)
const renameDialogVisible = ref(false)

// 编辑分类表单
const renameCategoryForm = ref<{ id: number | null, name: string, pid: number | null }>({id: null, name: '', pid: null})

// 更新全部命令列表
function updateCommandList() {
  getAllCommandList().then((res: any) => {
    if (res.data.code === 200) {
      commands.value = res.data.data;
    } else {
      message("获取常用命令失败", 'error')
    }
  })
}

// 更新全部命令类别列表
function updateCategoryList() {

  let mockCategories = [];
  // 使用模拟数据替换后端请求
  getAllCommandCategoryList().then((res: any) => {
    if (res.data.code === 200) {
      mockCategories = res.data.data;
      mockCategories = mockCategories.filter((item: any) => item.id !== '0')
      categoriesFromBackend.value = mockCategories;
    } else {
      message('获取命令类别失败', 'error')
    }
  })

}

// 添加命令
function addCommand() {
  dialogTitle.value = '添加命令'
  currentCommand.value = {command: '', description: '', category: categoriesFromBackend.value[0]?.id}
  dialogVisible.value = true
}

// 编辑命令
function editCommand(data: any) {
  dialogTitle.value = '编辑命令'
  currentCommand.value = data.row;
  dialogVisible.value = true
}

// 保存命令
function saveCommand() {
  saveOrUpdateCommandItem(currentCommand.value).then((res: any) => {
    if (res.data.code === 200) {
      message('添加命令成功', 'success')
      updateCommandList();
      dialogVisible.value = false
    } else {
      message('保存命令失败', 'error')
    }
  })
}

// 删除命令
function deleteCommand(scope: any) {
  deleteCommandItem(scope.row.id).then((res: any) => {
    if (res.data.code === 200) {
      message('删除命令成功', 'success')
      updateCommandList();
    } else {
      message('删除命令失败', 'error')
    }
  })
}

// 分类点击事件
function handleCategorySelect(key: any, node: any) {
  console.log(key, node)
  if (key.id === '0') {
    updateCommandList();
  } else {
    queryCommandList({category: key.id}).then((res: any) => {
      if (res.data.code === 200) {
        commands.value = res.data.data
      } else {
        message('查询命令失败', 'error')
      }
    })
  }
  selectedCategoryId.value = key.id
}

// 搜索内容重置，并加载全部命令
function searchReset() {
  searchCmdKeyword.value = ''
  searchDesKeyword.value = ''
  updateCommandList();
}

// 搜索按钮点击事件
function searchCommands() {
  queryCommandList({command: searchCmdKeyword.value, description: searchDesKeyword.value}).then((res: any) => {
    if (res.data.code === 200) {
      commands.value = res.data.data
    } else {
      message('查询命令失败', 'error')
    }
  })
}

// 添加新分类
function addNewCategory() {
  // 验证分类名称是否已存在
  console.log("添加分类", newCategory.value)

  saveOrUpdateCommandCategory(newCategory.value).then((res: any) => {
    if (res.data.code === 200) {
      message('分类添加成功')
      updateCategoryList()
    } else {
      message('分类添加失败', 'error')
    }
  })

  // 关闭对话框并重置
  showAddCategoryDialog.value = false
  newCategory.value = {name: '', pid: '0'}
  message('分类添加成功')
}

// 显示右键菜单
function showContextMenu(event: any, category: any) {
  // 阻止默认右键菜单
  event.preventDefault();
  // 不显示"全部"分类的右键菜单
  if (category.id === '0') return;
  contextMenuPosition.value = {x: event.clientX, y: event.clientY};
  selectedCategoryItem.value = category;
  contextMenuVisible.value = true;
  // 点击其他区域关闭菜单
  document.addEventListener('click', closeContextMenu);
}

// 关闭右键菜单
function closeContextMenu() {
  contextMenuVisible.value = false;
  document.removeEventListener('click', closeContextMenu);
}

// 编辑分类
function renameCategory() {
  renameCategoryForm.value.name = selectedCategoryItem.value.name;
  renameCategoryForm.value.id = selectedCategoryItem.value.id;
  renameCategoryForm.value.pid = selectedCategoryItem.value.pid;

  renameDialogVisible.value = true;
  contextMenuVisible.value = false;
}

// 编辑分类
function confirmRename() {
  saveOrUpdateCommandCategory({
    id: renameCategoryForm.value.id,
    pid: renameCategoryForm.value.pid,
    name: renameCategoryForm.value.name
  }).then((res: any) => {
    if (res.data.code == 200) {
      message("编辑分类成功")
      updateCategoryList();
      updateCommandList();
      renameDialogVisible.value = false;
    } else {
      message("编辑分类失败", 'error')
    }
  })

}

// 删除分类
function deleteCategory() {
  contextMenuVisible.value = false;

  queryCommandList({category: selectedCategoryItem.value.id}).then((res: any) => {
    if (res.data.code == 200) {
      if (res.data.data && res.data.data.length > 0) {
        message('该分类下存在命令，无法删除', 'error');
        return;
      }

      ElMessageBox.confirm('确定要删除该分类吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除
        deleteCommandCategory({id: selectedCategoryItem.value.id}).then((res: any) => {
          if (res.data.code === 200) {
            message('分类删除成功');
            updateCategoryList();
          } else {
            message('分类删除失败', 'error');
          }
        })
      }).catch(() => {
        // 取消删除
      });

    } else {
      message("根据类别查询命令失败", 'error')
    }
  })
}

// 在此分类上添加命令
function addCommandToCategory() {
  contextMenuVisible.value = false;
  dialogTitle.value = '添加命令';
  currentCommand.value = {command: '', description: '', category: selectedCategoryItem.value?.id};
  dialogVisible.value = true;
}

const treeCategories = computed(() => {
  const categories = [...categoriesFromBackend.value];
  const map = new Map();
  const roots: any[] = [];

  // 添加"全部"分类作为根节点
  roots.push({
    id: '0',
    name: '全部',
    children: [],
    isAll: true
  });

  // 首先将所有分类放入映射表
  categories.forEach((category: any) => {
    map.set(category.id, {...category, children: []});
  });

  // 然后构建树形结构
  categories.forEach(category => {
    const parent = map.get(category.pid);
    if (parent) {
      parent.children.push(map.get(category.id));
    } else if (category.pid === '0') {
      roots[0].children.push(map.get(category.id));
    }
  });

  return roots;
})

onMounted(() => {
  updateCommandList();
  updateCategoryList();
})

</script>

<style scoped>
.el-table {
  margin-top: 20px;
}

::v-deep .el-tree-node__content {
  padding: 8px !important;
  height: auto !important;
  white-space: normal !important;
  line-height: 1.5;
}

::v-deep .el-tree-node {
  padding-left: 8px;
}

::v-deep .el-tree-node__children {
  padding-left: 16px;
}

::v-deep .el-tree-node__content:hover {
  background-color: #f5f7fa;
}

/* 全部分类样式 */
::v-deep .el-tree-node__content .el-tree-node__label:first-child {
  font-weight: bold;
  color: #626AEF;
}
</style>